<template>
  <div class="app-container">
    <!-- 侧边栏 -->
    <aside class="sidebar" :class="{ collapsed: isSidebarCollapsed }">
      <!-- 侧边栏头部 -->
      <div class="sidebar-header">
        <h2>MarkNote</h2>
        <div class="header-buttons">
          <el-button type="primary" size="small" circle class="new-note-btn" @click="createNewNote" title="新建笔记">
            <el-icon>
              <Plus />
            </el-icon>
          </el-button>
        </div>
      </div>

      <!-- 侧边栏笔记列表 -->
      <div class="notes-list">
        <el-menu :default-active="currentNote?.path || ''" class="el-menu-vertical" @select="handleNoteSelect">
          <!-- 笔记列表 -->
          <template v-if="notesList.length > 0">
            <el-menu-item v-for="(note) in notesList" :key="note.path" :index="note.path"
              :style="{ paddingLeft: (12 + note.depth * 15) + 'px' }"
              @contextmenu.prevent="showContextMenu($event, note)" draggable="true"
              @dragstart="handleDragStart($event, note)" @dragover.prevent="handleDragOver($event, note)"
              @drop="handleDrop($event, note)">

              <!-- 分组：带展开/折叠图标 -->
              <el-icon v-if="note.hasChildren" class="expand-icon" @click.stop="toggleGroup(note.path)"
                style="margin-right: 0px; cursor: pointer;font-size: 14px">
                <component :is="expandedGroups.has(note.path) ? ArrowDownBold : ArrowRightBold" />
              </el-icon>
              <el-icon v-else style="margin-right: 0px;font-size: 14px">
                <Document />
              </el-icon>

              <span class="note-name">
                {{ note.name }}
              </span>
            </el-menu-item>
          </template>

          <!-- 无笔记提示 -->
          <el-empty v-else description="暂无笔记" class="no-notes-tip">
            <el-button type="primary" size="small" @click="createNewNote">
              <el-icon>
                <Plus />
              </el-icon>
              <span>新建笔记</span>
            </el-button>
          </el-empty>
        </el-menu>
      </div>
    </aside>

    <!-- 编辑区域 -->
    <main class="editor-container">
      <div v-if="!currentNote" class="no-note">
        <p>请选择或新建一个笔记</p>
      </div>
      <div v-else class="editor-wrapper">
        <div class="editor-header">
          <div class="title-container">
            <el-button type="text" size="large" class="sidebar-toggle-btn" @click="toggleSidebar" title="折叠/展开侧边栏">
              <el-icon>
                <component :is="isSidebarCollapsed ? ArrowRight : ArrowLeft" />
              </el-icon>
            </el-button>
            <el-input v-model="noteTitle" ref="titleInputRef" @blur="handleTitleChange"
              @keydown.enter.prevent="handleTitleChange" placeholder="笔记标题" size="large" clearable />
          </div>
          <span v-if="currentNote?.updated" class="note-updated-time">{{ formatUpdateTime(currentNote.updated) }}</span>
        </div>
        <MdEditor v-model="editorContent" :preview="true" :editor-id="'main-editor'" @change="handleContentChange" />
      </div>
    </main>

    <!-- 右键菜单 -->
    <div v-if="contextMenuVisible" class="context-menu" :style="{ left: contextMenuX + 'px', top: contextMenuY + 'px' }"
      @click.stop>
      <div class="context-menu-item rename-item" @click="renameNote" v-if="selectedNote">
        <el-icon class="context-menu-icon">
          <Edit />
        </el-icon>
        <span>重命名</span>
      </div>

      <!-- 降级：仅当不是第一个笔记，且存在前一个顶级笔记 -->
      <div class="context-menu-item" @click="demoteNote"
        v-if="selectedNote && !selectedNote.isGroup && findPreviousTopLevelNote(selectedNote.path)">
        <el-icon class="context-menu-icon">
          <Bottom />
        </el-icon>
        <span>降级为子页</span>
      </div>

      <!-- 升级 -->
      <div class="context-menu-item" @click="promoteNote" v-if="selectedNote && selectedNote.parent">
        <el-icon class="context-menu-icon">
          <Top />
        </el-icon>
        <span>升级为父页</span>
      </div>

      <div class="context-menu-divider"
        v-if="(selectedNote && selectedNote.parent) || (selectedNote && !selectedNote.isGroup && findPreviousTopLevelNote(selectedNote.path))">
      </div>

      <div class="context-menu-item delete-item" @click="deleteSelectedNote" v-if="selectedNote">
        <el-icon class="context-menu-icon">
          <Delete />
        </el-icon>
        <span>删除笔记</span>
      </div>
    </div>
  </div>
</template>

<script setup>
// 导入必要的模块和组件
import { ref, onMounted, onUnmounted } from 'vue'
import { MdEditor } from 'md-editor-v3'
import { Plus, Delete, Edit, Document, Top, Bottom, ArrowDownBold, ArrowRightBold, ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'

// ========定义状态变量=========
// 笔记数据相关状态
const notesList = ref([])        // 所有笔记列表
const currentNote = ref(null)    // 当前打开的笔记
const editorContent = ref('')    // 编辑器内容
const noteTitle = ref('')        // 笔记标题
const isModified = ref(false)    // 笔记是否被修改
const draggedNote = ref(null)    // 当前拖动的笔记

// UI相关状态
const contextMenuVisible = ref(false)  // 右键菜单显示状态
const contextMenuX = ref(0)       // 右键菜单X坐标
const contextMenuY = ref(0)       // 右键菜单Y坐标
const selectedNote = ref(null)    // 当前选中的笔记
const titleInputRef = ref(null)   // 标题输入框引用
const isSidebarCollapsed = ref(false)  // 侧边栏是否折叠

const expandedGroups = ref(new Set())     // 展开的分组路径列表
const noteTree = ref([]) // 保存原始树形结构

// 自动保存计时器
let autoSaveTimer = null

// ========生命周期钩子=========
// 组件挂载时初始化
onMounted(async () => {
  // 加载笔记列表
  await loadNotesList()

  // 添加全局事件监听
  document.addEventListener('click', closeContextMenu)
  document.addEventListener('keydown', handleKeydown)
})

// 组件卸载时清理资源
onUnmounted(() => {
  // 清理事件监听和计时器
  document.removeEventListener('click', closeContextMenu)
  document.removeEventListener('keydown', handleKeydown)
  if (autoSaveTimer) {
    clearTimeout(autoSaveTimer)
  }
})

// ========笔记核心操作函数=========

// 加载笔记列表
async function loadNotesList() {
  try {
    const flatNotes = await window.electronAPI.getNotesList()

    const noteMap = new Map()
    flatNotes.forEach(note => {
      noteMap.set(note.path, { ...note, children: [] })
    })

    const rootNotes = []
    for (const note of noteMap.values()) {
      if (note.parent && noteMap.has(note.parent)) {
        noteMap.get(note.parent).children.push(note)
      } else {
        rootNotes.push(note)
      }
    }

    function sortNotes(list) {
      list.sort((a, b) => a.sort - b.sort)
      for (const item of list) {
        if (item.children) sortNotes(item.children)
      }
    }
    sortNotes(rootNotes)

    function markHasChildren(notes) {
      for (const note of notes) {
        note.hasChildren = note.children && note.children.length > 0
        if (note.children) markHasChildren(note.children)
      }
    }
    markHasChildren(rootNotes)

    // 保存树结构
    noteTree.value = rootNotes

    // 初始时全部展开（或根据 expandedGroups）
    flattenNotes()

    // 保持当前笔记逻辑
    if (currentNote.value) {
      const updatedNote = notesList.value.find(note => note.path === currentNote.value.path)
      if (updatedNote) {
        currentNote.value = updatedNote
        if (noteTitle.value !== updatedNote.name) {
          noteTitle.value = updatedNote.name
        }
      }
    }

    if (notesList.value.length > 0 && !currentNote.value) {
      await openNote(notesList.value[0])
    }
  } catch (error) {
    console.error('加载笔记列表失败:', error)
    notesList.value = []
    noteTree.value = []
  }
}

// 处理拖动开始
function handleDragStart(event, note) {
  draggedNote.value = note
  event.dataTransfer.effectAllowed = 'move'
}

// 处理拖动悬停
function handleDragOver(event, note) {
  event.preventDefault()
  event.dataTransfer.dropEffect = 'move'
}

// 处理放置
async function handleDrop(event, targetNote) {
  event.preventDefault()

  if (!draggedNote.value || draggedNote.value.path === targetNote.path) {
    draggedNote.value = null
    return
  }

  // 创建新的笔记列表副本
  const newNotesList = [...notesList.value]

  // 找到拖动笔记和目标笔记的索引
  const draggedIndex = newNotesList.findIndex(note => note.path === draggedNote.value.path)
  const targetIndex = newNotesList.findIndex(note => note.path === targetNote.path)

  // 从原位置移除拖动的笔记
  const [removedNote] = newNotesList.splice(draggedIndex, 1)

  // 插入到新位置
  newNotesList.splice(targetIndex, 0, removedNote)

  // 更新所有笔记的排序字段
  const noteSorts = newNotesList.map((note, index) => ({
    path: note.path,
    sort: index
  }))

  try {
    // 调用主进程更新排序
    await window.electronAPI.updateNoteSort(noteSorts)

    // 重新加载笔记列表以反映排序变化
    await loadNotesList()
  } catch (error) {
    console.error('更新排序失败:', error)
    ElMessage.error('更新排序失败')
  } finally {
    draggedNote.value = null
  }
}

// 切换笔记分组展开/收起
function toggleGroup(groupPath) {
  if (expandedGroups.value.has(groupPath)) {
    expandedGroups.value.delete(groupPath)
  } else {
    expandedGroups.value.add(groupPath)
  }
  flattenNotes()
}

// 展开/收起分组时刷新笔记列表
function flattenNotes() {
  function flatten(nodes, depth = 0) {
    let result = []
    for (const node of nodes) {
      result.push({ ...node, depth })
      if (node.hasChildren && expandedGroups.value.has(node.path)) {
        result = result.concat(flatten(node.children, depth + 1))
      }
    }
    return result
  }
  notesList.value = flatten(noteTree.value)
}

// 打开笔记
async function openNote(note) {
  try {
    const content = await window.electronAPI.readNote(note.path)
    currentNote.value = note
    noteTitle.value = note.name || '未命名笔记'
    editorContent.value = content || ''
    isModified.value = false

    // 清除之前的计时器并设置新的自动保存计时器
    if (autoSaveTimer) {
      clearTimeout(autoSaveTimer)
    }
    autoSaveTimer = setTimeout(() => {
      if (isModified.value && currentNote.value) {
        saveNote()
      }
    }, 1000)
  } catch (error) {
    console.error('打开笔记失败:', error)
    ElMessage.error('打开笔记失败')
  }
}

// 保存笔记
async function saveNote() {
  if (!currentNote.value) return

  try {
    const result = await window.electronAPI.saveNote({
      path: currentNote.value.path,
      content: editorContent.value
    })

    // 更新笔记标题（如果有变化）
    if (result?.title && result.title !== noteTitle.value) {
      noteTitle.value = result.title
    }

    isModified.value = false

    // 重新加载笔记列表以更新显示，但保持当前选中的笔记
    const currentPath = currentNote.value.path
    await loadNotesList()

    // 确保重新加载后仍然选中当前笔记
    if (currentPath) {
      const note = notesList.value.find(n => n.path === currentPath)
      if (note) {
        currentNote.value = note
      }
    }
  } catch (error) {
    console.error('保存笔记失败:', error)
    alert('保存笔记失败')
  }
}

// 新建笔记
async function createNewNote() {
  try {
    const newNote = await window.electronAPI.createNote()
    await loadNotesList()
    await openNote(newNote)
  } catch (error) {
    console.error('创建笔记失败:', error)
    alert('创建笔记失败')
  }
}

// 删除笔记
async function deleteSelectedNote() {
  if (!selectedNote.value) return

  try {
    await ElMessageBox.confirm(
      `确定要删除笔记吗？`,
      '确认',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )

    await window.electronAPI.deleteNote(selectedNote.value.path)

    // 如果删除的是当前打开的笔记，清除当前笔记
    if (currentNote.value && currentNote.value.path === selectedNote.value.path) {
      currentNote.value = null
      editorContent.value = ''
      isModified.value = false
    }

    await loadNotesList()
    closeContextMenu()
  } catch (error) {
    // 用户取消删除不算错误
    if (error !== 'cancel') {
      console.error('删除笔记失败:', error)
      ElMessage.error('删除笔记失败')
    }
  }
}

// ========侧边栏控制函数=========

// 切换侧边栏折叠状态
function toggleSidebar() {
  isSidebarCollapsed.value = !isSidebarCollapsed.value
}

// ========编辑器相关函数=========

// 处理编辑器内容变化
function handleContentChange(value) {
  editorContent.value = value || ''
  isModified.value = true

  // 重置自动保存计时器
  if (autoSaveTimer) {
    clearTimeout(autoSaveTimer)
  }
  autoSaveTimer = setTimeout(() => {
    if (isModified.value && currentNote.value) {
      saveNote()
    }
  }, 1000)
}

// 处理标题变更
async function handleTitleChange() {
  if (!currentNote.value || noteTitle.value === currentNote.value.name) return

  try {
    await window.electronAPI.updateNoteTitle({
      path: currentNote.value.path,
      title: noteTitle.value
    })

    // 更新当前笔记对象和列表
    currentNote.value.name = noteTitle.value
    await loadNotesList()

    // 失去焦点并聚焦到编辑器
    if (titleInputRef.value) {
      const inputEl = titleInputRef.value.$el.querySelector('input')
      if (inputEl) {
        inputEl.blur()
      }
    }

    // 延迟聚焦到Markdown编辑器，确保DOM已更新
    setTimeout(() => {
      const editorEl = document.querySelector('#main-editor .markdown-body, #main-editor .editor-container')
      if (editorEl) {
        editorEl.focus()
      }
    }, 100)
  } catch (error) {
    console.error('更新笔记标题失败:', error)
    // 恢复原标题
    noteTitle.value = currentNote.value.name
    alert('更新笔记标题失败')
  }
}

// ========UI交互函数=========

// 处理笔记选择
async function handleNoteSelect(key) {
  const note = notesList.value.find(note => note.path === key)
  if (note) {
    // 如果有未保存的修改，先保存当前笔记
    if (isModified.value && currentNote.value && currentNote.value.path !== note.path) {
      await saveNote()
    }
    // 打开新笔记
    await openNote(note)
  }
}

// ========右键菜单相关函数=========

// 显示右键菜单
async function showContextMenu(event, note) {
  event.preventDefault()
  selectedNote.value = note
  contextMenuX.value = event.clientX
  contextMenuY.value = event.clientY
  contextMenuVisible.value = true

  await handleNoteSelect(note.path)
}

// 关闭右键菜单
function closeContextMenu() {
  contextMenuVisible.value = false
  selectedNote.value = null
}

// 重命名笔记
async function renameNote() {
  if (!selectedNote.value) return

  // 确保选中的笔记已经打开
  if (currentNote.value?.path !== selectedNote.value.path) {
    await handleNoteSelect(selectedNote.value.path)
  }

  // 聚焦到标题输入框
  setTimeout(() => {
    if (titleInputRef.value) {
      const inputEl = titleInputRef.value.$el.querySelector('input')
      if (inputEl) {
        inputEl.focus()
      }
    }
  }, 100)

  closeContextMenu()
}

// 查找当前笔记之前的最近一个顶级笔记（parent 为 null）
function findPreviousTopLevelNote(currentPath) {
  const currentIndex = notesList.value.findIndex(n => n.path === currentPath)
  if (currentIndex <= 0) return null

  // 从当前往前遍历，找第一个 parent 为 null 的笔记
  for (let i = currentIndex - 1; i >= 0; i--) {
    const note = notesList.value[i]
    if (!note.parent) {
      return note
    }
  }
  return null
}

// 降级为子页
async function demoteNote() {
  if (!selectedNote.value) return

  const targetParent = findPreviousTopLevelNote(selectedNote.value.path)
  if (!targetParent) {
    ElMessage.warning('前面没有可作为父级的笔记')
    return
  }

  try {
    await window.electronAPI.setNoteAsChild({
      childPath: selectedNote.value.path,
      parentPath: targetParent.path
    })
    await loadNotesList()
    closeContextMenu()
  } catch (error) {
    console.error('降级失败:', error)
    ElMessage.error('降级失败')
  }
}

// 升级为父页
async function promoteNote() {
  if (!selectedNote.value?.parent) return
  try {
    await window.electronAPI.promoteNoteToTop(selectedNote.value.path)
    await loadNotesList()
    closeContextMenu()
  } catch (error) {
    console.error('升级失败:', error)
    ElMessage.error('升级失败')
  }
}

// 键盘快捷键处理
function handleKeydown(event) {
  // Ctrl+S 保存或新建笔记
  if ((event.ctrlKey || event.metaKey) && event.key === 's') {
    event.preventDefault()
    if (currentNote.value) {
      saveNote()
    } else {
      createNewNote()
    }
  }
}

// ========辅助函数=========

// 格式化更新时间
function formatUpdateTime(timestamp) {
  if (!timestamp) return ''

  try {
    const date = new Date(timestamp)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
    })
  } catch (error) {
    return ''
  }
}
</script>

<style>
/* 全局样式重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

/* 拖动相关样式 */
.el-menu-item[draggable="true"] {
  cursor: grab;
}

.el-menu-item[draggable="true"]:active {
  cursor: grabbing;
}

.el-menu-item[draggable="true"]:hover {
  background-color: #f5f7fa;
}

/* 拖动时的视觉反馈 */
.el-menu-item[draggable="true"].drag-over {
  background-color: #e6f7ff;
  border: 1px dashed #1890ff;
}

/* 笔记项通用样式 */
.el-menu-item {
  height: 40px !important;
  line-height: 40px !important;
  margin-bottom: 4px !important;
}

/* 主容器样式 */
.app-container {
  display: flex;
  height: 100vh;
  width: 100vw;
  overflow: hidden;
}

/* 侧边栏样式 */
.sidebar {
  width: 260px;
  height: 100%;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  transition: width 0.3s ease;
}

/* 侧边栏折叠状态 */
.sidebar.collapsed {
  width: 0;
  overflow: hidden;
}

/* 侧边栏切换按钮样式 */
.sidebar-toggle-btn {
  padding: 0 !important;
  color: #666 !important;
}

.sidebar-toggle-btn:hover {
  color: #409eff;
  background-color: #ecf5ff;
}

/* 侧边栏头部样式 */
.sidebar-header {
  padding: 12px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 0;
}

.sidebar-header h2 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

/* 头部按钮容器样式 */
.header-buttons {
  display: flex;
  gap: 8px;
  margin-left: auto;
}

/* 新建笔记按钮悬停效果 */
.new-note-btn:hover {
  background-color: #1976d2;
}

/* 笔记列表容器样式 */
.notes-list {
  flex: 1;
  overflow-y: auto;
}

/* 菜单样式调整 */
.el-menu-vertical {
  border-right: none;
  height: 100%;
  padding: 10px !important;
}

/* 笔记项选中效果 */
.el-menu-item.is-active {
  background-color: #e6f7ff !important;
  color: #4d7295 !important;
  font-weight: 500;
}

/* 笔记名称样式 */
.note-name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-left: 8px;
  cursor: pointer;
  display: inline-block;
  max-width: calc(100% - 40px);
}

/* 编辑器区域样式 */
.editor-container {
  flex: 1;
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* 无笔记提示样式 */
.no-note {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #666;
  font-size: 18px;
}

/* 侧边栏无笔记提示样式 */
.no-notes-tip {
  padding: 40px 20px;
}

.no-notes-tip .el-empty__description {
  margin-bottom: 20px;
}

/* 编辑器包装器样式 */
.editor-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 编辑器头部样式 */
.editor-header {
  padding: 12px 16px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

/* 标题容器样式 */
.title-container {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 更新时间显示样式 */
.note-updated-time {
  font-size: 12px;
  color: #999;
  white-space: nowrap;
}

/* 右键菜单样式 */
.context-menu {
  position: fixed;
  background-color: white;
  border-radius: 6px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  border: 1px solid #e0e0e0;
  padding: 4px 0;
  min-width: 160px;
}

/* 右键菜单项样式 */
.context-menu-item {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  cursor: pointer;
  font-size: 14px;
  color: #333;
}

/* 右键菜单项悬停效果 */
.context-menu-item:hover {
  background-color: #f5f5f5;
}

/* 右键菜单特定样式 */
.rename-item {
  color: #1890ff !important;
}

.delete-item {
  color: #ff4d4f !important;
}

/* 右键菜单图标样式 */
.context-menu-icon {
  margin-right: 8px;
  font-size: 14px;
}

/* 右键菜单分隔线样式 */
.context-menu-divider {
  height: 1px;
  background-color: #e0e0e0;
  margin: 2px 0;
}
</style>
